package com.ksl.kinglockguard.network;

import java.io.File;
import java.util.HashMap;

import android.app.DownloadManager;
import android.app.DownloadManager.Request;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;
import android.util.Log;

public class MyDownloadManager {
	private static final int DOWNLOAD_START = 1;
	private static final int DOWNLOAD_CANCEL = 2;
	private static final int DOWNLOAD_FAILED = 3;
	private static final int DOWNLOAD_SUCCESS = 4;
	private static MyDownloadManager downLoadManager = new MyDownloadManager();
	private HashMap<Long,String> urls = new HashMap<Long,String>();
	public static MyDownloadManager getInstance(){
		return downLoadManager;
	}

	private DownloadManager dm = null;
	public void download(Context context ,String url) {
		url = url+NetworkTask.getParams(context)+"&time="+System.currentTimeMillis()/1000;
		url = url.replace(" ", "%20");
		dm = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
		Request request = new Request(Uri.parse(url));
		request.setAllowedNetworkTypes(Request.NETWORK_MOBILE|Request.NETWORK_WIFI);
		request.setAllowedOverRoaming(false);
		request.setTitle("正在为您下载应用");
		File dir = Environment.getExternalStoragePublicDirectory("/.download/");
		if(!dir.exists()){
			dir.mkdirs();
		}
		request.setDestinationInExternalPublicDir("/.download", url.hashCode()+"");
		long id = dm.enqueue(request);
		int index = url.indexOf("?");
		urls.put(id, getAppIdFromParams(url.substring(index)));
		context.getApplicationContext().registerReceiver(receiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
	}
	
	private static String getAppIdFromParams(String params){
		String[] split = params.split("&");
		String appId = "";
		int size = split.length;
		for (int i = 0; i < size; i++) {
			String str = split[i];
			if(str.contains("appid")){
				appId = str.substring(str.indexOf("=")+1, str.length());
				break;
			}
		}
		return appId;
	}
	
	private BroadcastReceiver receiver = new BroadcastReceiver() {   
        @Override   
        public void onReceive(Context context, Intent intent) {   
        	long id = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0);
            //这里可以取得下载的id，这样就可以知道哪个文件下载完成了。适用与多个下载任务的监听  
            Log.v("intent", ""+ id);   
            queryDownloadStatus(context,id);   
        }   
    };   
      
    private void queryDownloadStatus(Context context, long id) {   
    	if(dm == null) {
    		return;
    	}
        DownloadManager.Query query = new DownloadManager.Query();   
        Cursor c = dm.query(query);   
        if(c.moveToFirst()) {   
            int status = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS));   
            switch(status) {   
            case DownloadManager.STATUS_PAUSED:   
            case DownloadManager.STATUS_PENDING:   
            case DownloadManager.STATUS_RUNNING:   
                //正在下载，不做任何事情  
                break;   
            case DownloadManager.STATUS_SUCCESSFUL:   
                //完成
                Log.v("wmm", "下载完成"+c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_FILENAME)));
                String appid = urls.get(id);
                NetworkTask.reportDownloadFinish(context,appid ,false);
                String path = c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_FILENAME));
                File file = new File(path);
                File tempFile = new File(Environment.getExternalStorageDirectory()+"/.download/"+file.getName()+".apk");
                file.renameTo(tempFile);
                openDownloadFile(context, tempFile.getAbsolutePath());
                context.unregisterReceiver(receiver);
                break;   
            case DownloadManager.STATUS_FAILED:   
                //清除已下载的内容，重新下载  
                Log.v("wmm", id+">>>>>STATUS_FAILED");  
                break;   
            }   
        }  
    } 
    
    private void openDownloadFile(Context context, String path){
    	 Intent intent =new Intent();
         intent.setAction("android.intent.action.VIEW"); 
         intent.addCategory("android.intent.category.DEFAULT");
         intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
         intent.setDataAndType(Uri.fromFile(new File(path)), "application/vnd.android.package-archive"); 
         context.startActivity(intent); 
    }
}  
